// miniprogram/pages/payAddress/payAddress.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    company_name: null,
    company_phone: null,
    info: [],
    shipping: "",
    token: '',
    show:false,
    selectData:[],
    index:0,
    indexid:0,
    yindex:0,
    yindexid:0,
    email: '',
    shipping_default:"",
    loadlist:false,
    company: [],
    bg_status: "none",
    info_status: "none",
    turnOn: 'inline-block',
    turnOff: 'none',
    selfValue: ""
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getcarts();
    this.setData({
      token: app.globalData.token
    })
  },

  userPerson: function (e) {

    this.setData({
      shipping_default:'weixin_self',
    })
    this.infoSubmit();
  },

  companyPerson: function (e) {

    this.setData({
      shipping_default: 'freeshipping',
    })
    this.companySubmit();
  },

  selectTap(){
    this.setData({
     show: !this.data.show
    });
    },

    optionTap(e){
      this.setData({
        yindex:this.data.Index,
        yindexid:this.data.indexid
       });
      let Index=e.currentTarget.dataset.index;//获取点击的下拉列表的下标
      let indexid=e.currentTarget.dataset.id;//获取点击id
      this.setData({
       index:Index,
       indexid:indexid,
       show:!this.data.show
      });
      },
 
  getcarts() {
    var that = this;

    app.getUserToken(function (err, token) {
      wx.request({
        url: app.globalData.url +'/index.php?_m=checkout/cart/get_cart&company_address=1&shipping=1&company_address_list=1',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: { auth_token: token },
        success: (res) => {
          if (res.data.status == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.getcarts();
          } else if (res.data.code == 0) {
            for(var key in res.data.data.company_address_list){
              if(res.data.data.company_address_list[key].address == res.data.data.company_address.address ){
                that.setData({
                  index:key
                })
                break;
              }
            }
            that.setData({
              shipping: res.data.data,
              company: res.data.data.company_address,
              loadlist:true,
              selectData:res.data.data.company_address_list,
              info: res.data.data.self_address,
              email: res.data.data.user_info.email
            })
          }
        },
        fail: (res) => {
          wx.showToast({
            title: '获取借口失败',
            duration: 2000
          })
        }
      })

    })
  },

  formSubmit: function (e) {
   
    if (!this.data.company.last_name && !this.data.info ){
      wx.showToast({
        icon:'none',
        title: '请完善地址',
        duration: 1500
      })
    }else if(this.data.shipping_default==''){
      wx.showToast({
        icon:'none',
        title: '请选择默认地址',
        duration: 1500
      })
    }else{
    wx.navigateTo({
        url: '../payment/payment'
      })
    }      
  },
  companyEdit: function (e) {
    this.setData({
      bg_status: "block"
    })
  },

  companySubmit: function (e) {
   
    let that = this;
    let company = that.data.company;
    let email =that.data.email;
    let is_self = 2;
    let id=that.data.indexid;
    let index=that.data.index;
    let last_name = '';
    let phone = '';
    let checkAddress=that.data.selectData[index];

    if(e){ 
      last_name = e.detail.value.company_name;
      phone = e.detail.value.company_phone.trim();
    }else{
      last_name = company.last_name;
      phone = company.phone.trim();
    }

    let zip = company.zip;
    var mobile = /^1[345789]\d{9}$/;
    var isMobile = mobile.test(phone);
    if (!last_name) {
      wx.showModal({
        title: "提示",
        content: '请完善姓名'
      })
      return false;
    }
    if (!isMobile) {
      wx.showModal({
        title: "提示",
        content: '你输入的电话不符，请重新检查填写'
      })
      return false;
    }

    app.getUserToken(function (err, token) {
      wx.showLoading({
        title: '加载中...',
      })
      wx.request({
        url: app.globalData.url + '/index.php?_m=checkout/process/info&v=v20190909b',
        data: {
          first_name: '', auth_token: token, "shipping_address[contact_name]": company.contact_name, "shipping_address[contact_phone]": company.contact_phone, email: email, save_shipping: 1, is_self: is_self, "shipping_address[address]": checkAddress.address, "shipping_address[city]": checkAddress.city, "shipping_address[last_name]": last_name, "shipping_address[phone]": phone, "shipping_address[province]": checkAddress.province, "shipping_address[zip]": zip, "id": id  },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: (res) => {
          wx.hideLoading();
          if (res.data.code == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.formSubmit();
          } else if (res.data.code == 0) {
            that.setData({
              shipping_default: 'freeshipping',
              company_name: last_name,
              company_phone: phone,
              company: res.data.data.company_address,

              bg_status: "none"
            })
          } else {
            that.setData({
              index:that.data.yindex,
              indexid:that.data.yindexid
            })
            wx.showModal({
              title: "提示",
              content: "请输入完整信息"
            })
            return false;
          }
        }
      })
    })
  },

  infoEdit: function (e) {
    this.setData({
      info_status: "block"
    })
  },

  infoSubmit: function (e) {
    let that = this;
    let info = this.data.info;
    let email = that.data.email;
    let address = '';
    let city = '';
    let is_self = 1;
    let last_name = '';
    let phone = '';
    let province = '';

    if(e){
        address = e.detail.value.address;
        city = e.detail.value.city;
        last_name = e.detail.value.last_name;
        phone = e.detail.value.phone.trim();
        province = e.detail.value.province;
    }else{
        address = info.address;
        city = info.city;
        last_name = info.last_name;
        phone = info.phone.trim();
        province = info.province;
    }
    var mobile = /^1[345789]\d{9}$/;
    var isMobile = mobile.test(phone);
    console.log(last_name);
    if (!last_name) {
      wx.showModal({
        title: "提示",
        content: '请输入正确的姓名'
      })
      return false;
    }
    if (!isMobile) {
      wx.showModal({
        title: "提示",
        content: '你输入的电话不符，请重新检查填写'
      })
      return false;
    }

    if (!province) {
      wx.showModal({
        title: "提示",
        content: '请输入省份'
      })
      return false;
    }
    if (!city) {
      wx.showModal({
        title: "提示",
        content: '请输入城市'
      })
      return false;
    }
    if (!address) {
      wx.showModal({
        title: "提示",
        content: '请输入地址'
      })
      return false;
    }

    app.getUserToken(function (err, token) {
      wx.showLoading({
        title: '加载中...',
      })
      wx.request({
        url: app.globalData.url + '/index.php?_m=checkout/process/info&v=v20190909b',
        data: { first_name: '', auth_token: token, email: email, save_shipping: 1, is_self: is_self, "shipping_address[address]": address, "shipping_address[city]": city, "shipping_address[last_name]": last_name, "shipping_address[phone]": phone, "shipping_address[province]": province, "shipping_address[zip]": '000000' },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: (res) => {
          wx.hideLoading();
          if (res.data.code == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.formSubmit();
          } else if (res.data.code == 0) {
            var uinfo =info;
            if(e){
              uinfo = e.detail.value
            }
            that.setData({
              shipping_default: 'weixin_self',
              info: uinfo,
              info_status: "none"
            })
          } else {
            wx.showModal({
              title: "提示",
              content: "请输入完整信息"
            })
            return false;
          }
        }
      })
    })

    
  },



  closeEdit: function (e) {

    this.setData({
      bg_status: "none"
    })
  },

  closeInfo: function (e) {

    this.setData({
      info_status: "none"
    })
  },

  onShareAppMessage: function () {
    app.globalData.uid = app.globalData.uid || wx.getStorageSync('uid') || 0;
    return {
      title: '深圳智汇创想科技有限责任公司员工福利购!',
      path: '/pages/index/index?fid=' + app.globalData.uid
    }
  }
})